<?php
/**
* phpCan - http://idc.anavallasuiza.com/
*
* phpCan is released under the GNU Affero GPL version 3
*
* More information at license.txt
*/

namespace data\formats;

defined('ANS') or die();

class Sort extends Formats implements iFormats {
	var $format = 'sort';

	public function check ($value) {
		$this->error = array();

		return $this->validate($value);
	}

	public function afterSave (\data\Data $Data, $values) {
		if ($values['value'][''] == $values['old_value']['']) {
			return true;
		}

		$id = $values['row_values']['id']['default'][''];

		$exists = $Data->selectCount(array(
			'table' => $this->table,
			'conditions' => array(
				'id !=' => $id,
				$this->name => $values['value']['']
			)
		));

		if (!$exists) {
			return true;
		}

		$query = array(
			'table' => $this->table,
			'conditions' => array(
				'id !=' => $id
			),
			'comment' => __('Moving the other sort values to keep a free gap for the current sort')
		);

		if ($values['value'][''] < $values['old_value']['']) {
			$query['data'][0] = $this->name.' = '.$this->name.' + 1';
			$query['conditions'][$this->name.' >='] = $values['value'][''];
		} else {
			$query['data'][0] = $this->name.' = '.$this->name.' - 1';
			$query['conditions'][$this->name.' <='] = $values['value'][''];
			$query['conditions'][$this->name.' >'] = $values['old_value'][''];
		}

		$Data->Database->update($query);

		return true;
	}

	public function settings ($settings) {
		$this->settings = $this->setSettings($settings, array(
			'' => array(
				'db_type' => 'integer',

				'length_max' => 8,
				'unsigned' => true
			)
		));

		return $this->settings;
	}
}
?>